package com.hxzy.controller.front;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.dto.PageDTO;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.dto.MerchandiserSearchDTO;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.ExistsService;
import com.hxzy.service.MerchandiserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 前端商家API
 * @author Administrator
 */
@ApiOperation(value = "前端商家API")
@RestController
@RequestMapping(value = "/front/merchandiser")
public class FrontMerchandiserController extends BaseController {

    @Autowired
    private ExistsService existsService;

    @Autowired
    private MerchandiserService merchandiserService;

    @ApiOperation(value = "验证账户是否被注册过")
    @GetMapping(value = "/accountUsed/{phone}")
    public R accountUsed(@PathVariable(value = "phone") String phone){
        //验证电话号码的有效性
        if( StrUtil.isBlank(phone) ||   !Validator.isMobile(phone)){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        int count = this.existsService.loginNameExists(phone);

        R r=R.ok();
        if(count>0){
            r.setData(AckCode.USER_HAS_ACCOUNT.getMsg());
        }
        return r;
    }

    @ApiOperation(value = "商家注册申请")
    @PostMapping(value = "/register")
    public R register(@RequestBody @Valid Merchandiser  merchandiser){

        int count = this.existsService.loginNameExists(merchandiser.getLoginName());
        if(count>0){
            return R.build(AckCode.USER_HAS_ACCOUNT);
        }

        //密码加密
        String pwd= BCrypt.hashpw(merchandiser.getLoginPwd());
        merchandiser.setLoginPwd(pwd);

        merchandiser.setStatus((byte) 1);
        merchandiser.setCreateBy(merchandiser.getName());
        merchandiser.setCreateTime(new Date());
        boolean save = this.merchandiserService.save(merchandiser);
        return  super.toR(save);
    }


    @ApiOperation(value = "前端获取商户信息")
    @GetMapping(value = "/data")
    public R search(PageDTO pageDTO){
        super.startPageHelper();
        MerchandiserSearchDTO merchandiserSearchDTO=new MerchandiserSearchDTO();
        merchandiserSearchDTO.setStatus((byte)0);
        List<Merchandiser> merchandiserList = this.merchandiserService.search(merchandiserSearchDTO);
        return super.pageToPageVO(merchandiserList);
    }

}
